<template>
  <view class="container">
    <!-- <view class="map-search" style="margin: 20rpx" @click="selectCity">
      <input disabled type="text" class="u-text" placeholder="搜索小区名称" />
      <text class="u-btn">搜索</text>
    </view> -->

    <!-- <view class="l-map">
      <map
        id="map"
        style="width: 100%"
        :style="{ height: screenHeight + 'px' }"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="scale"
        @labeltap="handleLabelTap"
      />
    </view> -->
    <!--http://192.168.101.105:5173-->
    <!--    https://bz.txjmk.com/map-->
    <web-view :src="`http://localhost:5174/#/?params=${webViewUrl}`" @message="handleLabelTap"></web-view>
  </view>
</template>

<script>
import store from '@/store';
import { version } from '@/config/app.js';

export default {
  data() {
    return {
      timer: null,
      screenHeight: 800,
      pageNo: 1,
      pageSize: 100,
      total: 1, //数据总条数
      scale: 14, //缩放级别，取值范围为3-20
      // 标记点
      markers: [
        // 第一项作为当前位置的标记
        {
          id: 1,
          latitude: 39.909,
          longitude: 116.39742,
          iconPath: this.$pictureBaseUrl + '/static/imgs/icon-location.png',
          width: 20,
          height: 20,
        },
      ],
      teamLeaderId: '', //当前登录主理人id
      rowData: {},
      webViewUrl: '',
    };
  },
  computed: {
    // 总页数
    pageCount() {
      return this.total == 0 ? 0 : Math.ceil(this.total / this.pageSize);
    },
    // 中心经度
    longitude() {
      return this.markers?.[0]?.longitude;
    },
    // 中心纬度
    latitude() {
      return this.markers?.[0]?.latitude;
    },
  },
  onLoad() {
    this.init();
    window.addEventListener('message', this.handleLabelTap);
  },
  // onShow() {
  //   this.startAutoLoadTimer(); // 启动定时器轮询数据
  // },
  // onHide() {
  //   this.clearAutoLoadTimer();
  // },
  // onUnload() {
  //   this.clearAutoLoadTimer();
  // },
  methods: {
    async init() {
      this.screenHeight = uni.getSystemInfoSync()?.windowHeight || 800;
      this.teamLeaderId = uni.getStorageSync('teamLeaderId');
      //获取当前的地理位置为中心点
      // await this.getCenterMarker();
      this.getList();
    },
    // 点击label时触发，e.detail = {markerId}
    handleLabelTap(e) {
      if (!e.data.type) return;
      console.log('eeee', e);
      const choose = e.data.data;
      const { webViewMessageType, communityId } = choose;
      if (webViewMessageType == 'popup') {
        uni.navigateTo({
          url: `/pages/link_community/confirm_link_address?type=link_community&addIds=${communityId}`,
        });
        return;
      }
      if (webViewMessageType == 'input') {
        this.selectCity();
      }
      return;
      const clickId = e.detail.markerId;
      const matched = this.markers.find(o => o.id == clickId);
      const name = matched.label.content; //小区名称

      // type：
      // 未关联小区为0
      // 当前登录主理人关联为1
      // 其他主理人关联为2

      //被当前登录的主理人关联
      if (matched?.info?.type === 1) {
        return uni.showToast({
          title: `小区【${name}】已被我关联`,
          icon: 'none',
          duration: 1000,
        });
      }

      //被其他主理人关联
      if (matched?.info?.type === 2) {
        return uni.showToast({
          title: `小区【${name}】已被其他主理人	关联`,
          icon: 'none',
          duration: 1000,
        });
      }

      uni.showModal({
        title: '温馨提示',
        content: `是否关联【${name}】?`,
        success: res => {
          if (res.confirm) {
            //isCanBuy 当前登录的主理人是否可以购买该小区 1：可以 0：不能
            if (matched.info.isCanBuy === 1) {
              const communityId = matched.info.id;
              order
                .getPayPreviewByTeamLeaderIdAndCommunityId({
                  teamLeaderId: this.teamLeaderId,
                  communityId,
                })
                .then(res => {
                  if (res.code === 0) {
                    // this.$set(matched.label, 'borderColor', '#59efa4')
                    // this.$set(matched.label, 'color', '#59efa4')
                    // this.$set(matched.info, 'type', 1)
                    uni.navigateTo({
                      url: `/pages/link_community/confirm_link_address?type=link_community&addIds=${communityId}`,
                    });
                  }
                });
            } else {
              uni.showToast({
                title: '主理人只允许购买上级区域名下的小区',
                icon: 'none',
                duration: 1000,
              });
            }
          }
        },
      });
    },
    startAutoLoadTimer() {
      this.clearAutoLoadTimer();
      this.autoLoadTimer = setInterval(() => {
        if (this.pageNo > this.pageCount) {
          this.clearAutoLoadTimer();
        } else {
          this.getList();
        }
      }, 2000); // 每5秒加载一次
    },
    clearAutoLoadTimer() {
      if (this.autoLoadTimer) {
        clearInterval(this.autoLoadTimer);
        this.autoLoadTimer = null;
      }
    },
    //点击搜索框或搜索按钮时跳转小区搜索页面
    selectCity() {
      const data = {
        longitude: this.longitude,
        latitude: this.latitude,
        teamLeaderId: this.teamLeaderId,
      };
      uni.navigateTo({
        url: `pages/link_community/mapSelect-list?data=${JSON.stringify(data)}`,
      });
    },
    getList() {
      // console.log(this.pageNo, this.pageCount);
      // if (this.pageNo > this.pageCount) return;
      // const data = {
      //   pageNo: this.pageNo,
      //   pageSize: this.pageSize,
      //   longitude: this.longitude,
      //   latitude: this.latitude,
      //   isPageIndex: 1,
      //   teamLeaderId: this.teamLeaderId,
      // };
      this.webViewUrl = JSON.stringify({
        type: 'multi',
        pageName: 'h5_link_community',
        token: store.getters.token,
        version,
        // longitude: this.longitude,
        // latitude: this.latitude,
        latitude: 39.909,
        longitude: 116.39742,
        teamLeaderId: this.teamLeaderId,
      });
      return;
      home.getCommunityPage(data).then(res => {
        if (res.code === 0) {
          const list = res?.data?.list || [];
          this.pageNo++; //页码累加
          this.total = res?.data?.total; // 更新总数据量
          console.log('getList:', list);
          const markers = list.map(item => {
            // 未关联小区为0
            // 当前登录主理人关联为1
            // 其他主理人关联为2
            const type = !item?.teamLeaderId ? 0 : item?.teamLeaderId === this.teamLeaderId ? 1 : 2;
            return {
              id: item.id,
              latitude: item.communityLatitude,
              longitude: item.communityLongitude,
              width: 12,
              height: 20,
              label: {
                content: item.communityName,
                borderColor: type === 1 ? '#59efa4' : type === 2 ? '#409eff' : '#fa3534',
                color: type === 1 ? '#59efa4' : '#333',
                bgColor: '#fff',
                borderWidth: 2,
                anchorX: '-8',
                anchorY: '-63',
                textAlign: 'center',
                borderRadius: 5,
                padding: 10,
              },
              info: {
                id: item.id,
                type,
                isCanBuy: item.isCanBuy, //当前登录的主理人是否可以购买该小区 1：可以 0：不能
              },
            };
          });
          this.markers.push(...markers);
        }
      });
    },
    // 获取当前的地理位置为中心点
    getCenterMarker() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          success: res => {
            console.log('getLocation：', res);
            this.$set(this.markers[0], 'latitude', res?.latitude);
            this.$set(this.markers[0], 'longitude', res?.longitude);
            resolve();
          },
          fail: err => {
            console.log('获取经纬度失败', err);
            reject();
          },
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
}

.map-search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16rpx 0;
  line-height: 60rpx;
  border: 1rpx solid #eee;
  border-radius: 50rpx;

  .u-text {
    flex: 1;
    line-height: 60rpx;
    padding-left: 30rpx;
    font-size: 26rpx;
    color: #333;
  }

  .u-btn {
    display: block;
    width: 120rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 26rpx;
    color: #5ff0a3;
    text-align: center;
  }
}
</style>
